package com.dkm.ec.activity.repository.impl;

import com.dkm.base.core.helper.SpringHelper;
import com.dkm.base.db.persistence.dao.IQueryDao;
import com.dkm.biz.repository.AbstractRepository;
import com.dkm.ec.activity.domain.LimitBuyActivitySku;
import com.dkm.ec.activity.persistence.dao.LimitBuyActivitySkuDao;
import com.dkm.ec.activity.persistence.dao.LimitBuyActivitySkuQueryDao;
import com.dkm.ec.activity.persistence.entity.LimitBuyActivitySkuPo;
import com.dkm.ec.activity.repository.LimitBuyActivitySkuRepository;
import com.dkm.ec.stock.persistence.dao.StockDao;
import com.dkm.ec.stock.persistence.dao.StockQueryDao;
import com.dkm.ec.stock.persistence.entity.StockPo;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hhq
 * @create 2017/8/14
 */
@Repository
public class LimitBuyActivitySkuRepositoryImpl extends AbstractRepository<String, LimitBuyActivitySkuPo, LimitBuyActivitySku> implements LimitBuyActivitySkuRepository {

    @Resource
    private LimitBuyActivitySkuQueryDao limitBuyActivitySkuQueryDao;
    @Resource
    private LimitBuyActivitySkuDao limitBuyActivitySkuDao;
    @Resource
    private StockQueryDao stockQueryDao;
    @Resource
    private StockDao stockDao;

    @Override
    public LimitBuyActivitySku newInstance() {
        LimitBuyActivitySku domain = SpringHelper.getBean(LimitBuyActivitySku.class);
        domain.setData(new LimitBuyActivitySkuPo());
        return domain;
    }

    @Override
    public LimitBuyActivitySku newInstance(LimitBuyActivitySkuPo po) {
        LimitBuyActivitySku domain = SpringHelper.getBean(LimitBuyActivitySku.class);
        domain.setData(po);
        return domain;
    }

    @Override
    public List<LimitBuyActivitySkuPo> findActivityGoodSkus(String partinId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("partinId", partinId);
        return limitBuyActivitySkuQueryDao.findByKey("findActivityGoodSkus", params);
    }

    @Override
    public List<LimitBuyActivitySkuPo> findNeedReturnStockSkus() {
        Map<String, Object> params = new HashMap<String, Object>();
        return limitBuyActivitySkuQueryDao.findByKey("findNeedReturnStockSkus", params);
    }

    @Override
    public void returnStock(List<LimitBuyActivitySkuPo> skuPos) {
        for(LimitBuyActivitySkuPo skuPo : skuPos) {
            // 增加总库存
            StockPo stockPo = stockQueryDao.get(skuPo.getStockid());
            stockPo.setQty(stockPo.getQty() + skuPo.getAvailableNum());
            stockDao.update(stockPo);
            // 更新sku.isReturnStock=1
            skuPo.setAvailableNum(0);
            skuPo.setIsReturnStock("1");
            limitBuyActivitySkuDao.update(skuPo);
        }
    }

    @Override
    protected IQueryDao<String, LimitBuyActivitySkuPo> getQueryDao() {
        return limitBuyActivitySkuQueryDao;
    }
}
